import { reqGetCode, reqRegister, reqLogin, reqLogintoken,reqLoginut } from '@/api'

const actions = {
  async getCode({ commit }, phone) {
    let result = await reqGetCode(phone)
    if (result.code == 200) {
      commit('GETCODE', result.data)
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  //注册
  async getRegister({ commit }, user) {
    let result = await reqRegister(user)
    console.log(result);
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  //登录
  async getLogin({ commit }, data) {
    let result = await reqLogin(data)
    if (result.code == 200) {
      commit('USERLOGIN', result.data.token)
      localStorage.setItem('TOKEN',result.data.token)
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  //获取登录信息
  async getUserInfo({commit}) {
    let result = await reqLogintoken()
    if (result.code == 200) {
      commit('GETUSERINFO',result.data)
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  //推出登录
  async userLogout({commit}) {
    let result = await reqLoginut()
    if (result.code == 200) {
      commit('LOGINUT')
      return 'ok'
    } else {
       return Promise.reject(new Error('faile'))
  }
  }
}

const mutations = {
  GETCODE(state, code) {
    state.code = code
  },
  USERLOGIN(state, token) {
    state.token = token
  },
  GETUSERINFO(state, userInfo) {
    state.userInfo =userInfo
  },
  LOGINUT(state) {
    state.token = ''
    state.userInfo = {}
    localStorage.removeItem('TOKEN')
  }
}

const state = {
  code: '',
  token: localStorage.getItem('TOKEN') ,
  userInfo:{}
}

const getters = {
}

export default {
  namespaced: true,
  state,
  actions,
  mutations,
  getters
}